package org.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
public class RouterConfiguration {

    // 在你的Spring Cloud Gateway过滤器或路由中注入DiscoveryClient
    @Autowired
    private DiscoveryClient discoveryClient;

    public boolean isServiceAvailable(String serviceName) {
        // 根据服务名称获取所有的服务实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);

        // 如果服务实例列表为空，则服务不存在
        if (instances.isEmpty()) {
            return false;
        }

        // 可根据业务需要，进一步检查每个实例的状态、健康状况等

        return true;
    }

    @Bean
    public RouteLocator  customRouteLocator(RouteLocatorBuilder builder){





        return builder.routes()
                .route(route -> route.path("/out_doctor/**")
                        .uri("lb://his-medicalstaff-serv"))
                .route(route -> route.path("/common_page/**")
                        .uri("lb://his-commonpage-serv"))
                .route(route -> route.path("/regis/**")
                        .uri("lb://his-registerpeople-serv"))
                .route(route -> route.path("/patient/**")
                        .uri("lb://his-patient-serv"))
                .route(route -> route.path("/medical_technician/**")
                        .uri("lb://his-medicaltechstaff-serv"))
                .route(route -> route.path("/expense/**")
                        .uri("lb://his-financialstaff-serv"))
                .route(route -> route.path("/drug/**")
                        .uri("lb://his-drugstore-serv"))
                .route(route -> route.path("/admin/**")
                        .uri("lb://his-administrator-serv"))
                .build();
    }

//    @Bean
//    public CorsWebFilter corsFilter() {
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        CorsConfiguration config = new CorsConfiguration();
//        config.addAllowedOrigin("*");
//        config.setAllowCredentials(true);
//        config.addAllowedHeader("*");
//        config.addAllowedMethod("*");
//        source.registerCorsConfiguration("/**", config);
//
//        return new CorsWebFilter(source);
//    }


}
